package com.wangyadong.hobby.schedule.jobtask.passsalt;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @ClassName PassSalt
 * @Description TODO
 * @Authpr Antonio
 * @Data 2018-07-09 15:51
 */
public class PassSalt {
    /**
     * 生成盐
     *
     * @return
     */
    public static byte[] createSalt() {
        byte[] salt = new byte[16];
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.nextBytes(salt);
            return salt;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * 生成摘要
     *
     * @param password
     * @param salt
     * @return
     */
    public static byte[] digest(String password, byte[] salt) {

        try {
            MessageDigest msgDigest = MessageDigest.getInstance("SHA");
            if (salt != null && salt.length > 0) {
                msgDigest.update(salt);
            }

            byte[] digest = msgDigest.digest(password.getBytes());
            return digest;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public static String createCredential(String password) {
        return digest(password, createSalt()).toString();
    }

    public static void main(String[] args) {
        String credential1 = createCredential("123456");
        String credential2 = createCredential("123456");
        System.out.println(credential1.equals(credential2));
    }
}
